package com.sea.finance.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.Inventory;
import com.sea.finance.entity.InventoryStock;
import com.sea.finance.mapper.InventoryMapper;
import com.sea.finance.service.InventoryService;
import com.sea.finance.service.InventoryStockService;
import com.sea.physical.entity.CreateDespatchSku;
import com.sea.physical.service.CreateDespatchSkuService;
import com.sea.product.entity.Product;
import com.sea.product.service.ChannelService;
import com.sea.product.service.ProductService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/finance/inventoryStock")
public class InventoryStockController {

    @Autowired
    private InventoryStockService inventoryStockService;
    @Autowired
    private ProductService productService;

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/finance/InventoryStock/main";
    }

    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCost(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     InventoryStock inventoryStock) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<InventoryStock> list = inventoryStockService.findByCnd(inventoryStock);
        PageInfo<InventoryStock> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @ResponseBody
    @RequestMapping("/test")
    public AjaxReturn test() {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            List<Product> list = productService.getProduce(null);

            for(Product product:list){
                InventoryStock inventoryStock=new InventoryStock();
                BeanUtils.copyProperties(product,inventoryStock);
                inventoryStockService.save(inventoryStock);
            }
            result.setOk(true).setMsg("保存成功！");

        }  catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    @RequestMapping(value = "/export")
    @ResponseBody
    public void exportShipped(HttpServletRequest request, HttpServletResponse response,  InventoryStock inventoryStock) {
        List<InventoryStock> list = inventoryStockService.findByCnd(inventoryStock);
        String[] title = {"期间","渠道","SKU","产品名称","采购在产","国内仓库存","海外仓库存","实际在途(FBA)","实际在途(海外仓)","实际在途(海外仓-FBA)"};
        String fileName = "在途报表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "在途报表";
        String[][] content = new String[list.size()][10];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            InventoryStock obj = list.get(i);
            content[i][0] = obj.getStockDate();
            content[i][1] = obj.getProductPropertyName();
            content[i][2] = obj.getProductSku();
            content[i][3] = obj.getProductName();
            content[i][4] = obj.getProduceNumber()+"";
            content[i][5] = obj.getWareNumber()+"";
            content[i][6] = obj.getStockNumber()+"";
            content[i][7] = obj.getCreateNumber()+"";
            content[i][8] = obj.getCreateWareNumber()+"";
            content[i][9] = obj.getCreatePortNumber()+"";

        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
